﻿using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Extensions.Others;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.CommonModel;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using System.Linq;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// Agv车辆 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class Les_AgvController : ControllerBase
    {
        private readonly ILes_AgvServices _Les_AgvServices;
        private readonly IV_AgvServices _v_AgvServices;
        private readonly IUser _user;
        private readonly ILogger<Les_AgvController> _logger;

        public Les_AgvController(IV_AgvServices v_AgvServices, ILes_AgvServices Les_AgvServices, IUser user, ILogger<Les_AgvController> logger)
        {
            this._v_AgvServices = v_AgvServices;
            _Les_AgvServices = Les_AgvServices;
            _user = user;
            _logger = logger;
        }

        /// <summary> 
        /// 分页获取Agv车辆列表 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        public async Task<MessageModel<PageModel<Les_Agv>>> Get([FromBody] Les_AgvParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<Les_Agv, Les_AgvParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<Les_Agv>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }
            var data = await _Les_AgvServices.QueryPage(whereConditions.data, param.page, param.pageSize, " AgvName asc ");
            return new MessageModel<PageModel<Les_Agv>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };

        }

        /// <summary> 
        /// 获取Agv车辆全部列表 
        /// </summary> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<List<V_Agv>>> GetAllVehicles()
        {
            var dataList = await _v_AgvServices.Query();
            dataList = dataList.OrderBy(x => x.AgvName).ToList();
            return new MessageModel<List<V_Agv>>()
            {
                msg = "获取成功",
                success = true,
                response = dataList
            };
        }

        /// <summary> 
        /// 获取单个Agv车辆 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<Les_Agv>> Get(int id = 0)
        {
            return new MessageModel<Les_Agv>()
            {
                msg = "获取成功",
                success = true,
                response = await _Les_AgvServices.QueryById(id)
            };
        }

        /// <summary> 
        /// 新增Agv车辆 
        /// </summary> 
        /// <param name="request">要新增的Agv车辆对象</param> 
        /// <returns></returns> 
        [HttpPost]
        public async Task<MessageModel<string>> Post([FromBody] Les_Agv request)
        {
            try
            {
                #region 验证 
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Les_Agv, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                                        new ValidateModel(){ ChinaName="车辆名称",PropertyName="AgvName" },

                };
                retBody = ValidateDataHelper.CommonValidate<Les_Agv, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                #endregion

                request.CreateTime = request.ModifyTime = DateTime.Now;
                request.CreateBy = request.ModifyBy = _user.Name;
                request.CreateId = request.ModifyId = _user.ID;
                request.OperationRemark = "添加";
                var id = await _Les_AgvServices.Add(request);
                var success = id > 0;

                if (success)
                {
                    return MessageModel<string>.Success("添加成功", id.ObjToString());
                }
                return MessageModel<string>.Fail("添加失败");
            }
            catch (Exception ex)
            {
                _logger.LogError("新增Agv车辆出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("新增Agv车辆出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 更新Agv车辆 
        /// </summary> 
        /// <param name="request">要更新的Agv车辆对象</param> 
        /// <returns>更新结果</returns> 
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] Les_Agv request)
        {
            try
            {
                #region 验证 
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Les_Agv, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>()
                {
                                         new ValidateModel(){ ChinaName="主键",PropertyName="Id" },
                     new ValidateModel(){ ChinaName="车辆名称",PropertyName="AgvName" },

                };
                retBody = ValidateDataHelper.CommonValidate<Les_Agv, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                #endregion

                var dbObj = await _Les_AgvServices.QueryById(request.Id);
                if (dbObj == null)
                {
                    return MessageModel<string>.Fail("数据不存在!");
                }

                request.ModifyTime = DateTime.Now;
                request.ModifyBy = _user.Name;
                request.ModifyId = _user.ID;
                request.OperationRemark = "更新";
                var success = await _Les_AgvServices.Update(request);

                if (success)
                {
                    return MessageModel<string>.Success("更新成功", request.Id.ObjToString());
                }
                return MessageModel<string>.Fail("更新失败");
            }
            catch (Exception ex)
            {
                _logger.LogError("更新Agv车辆出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("更新Agv车辆出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 删除Agv车辆 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id = 0)
        {
            try
            {
                var data = new MessageModel<string>();
                if (id > 0)
                {
                    var detail = await _Les_AgvServices.QueryById(id);
                    if (detail != null)
                    {
                        data.success = await _Les_AgvServices.DeleteById(detail.Id);
                        if (data.success)
                        {
                            data.msg = "删除成功";
                            data.response = detail?.Id.ObjToString();
                        }
                    }
                    else
                    {
                        return MessageModel<string>.Fail("数据不存在!");
                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "删除失败,Agv车辆不存在";
                }
                return data;
            }
            catch (Exception ex)
            {
                _logger.LogError("删除Agv车辆出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("删除Agv车辆出现异常:" + ex.Message);
            }
        }

    }
}
